"""
    @File : redis_create_key.py 
    @Create : 2021/11/23 下午1:31 
    @Author : wx
    @Update : 2021/11/23 下午1:31 
    @License : (C)Copyright 2014-2021 SmartAHC All Rights Reserved 
    @Desc    :   Coding Below
    @Software: PyCharm
"""

#### 自定义缓存key
from functools import wraps
from django.core.cache import CacheHandler
from django.conf import settings

alias = settings.CACHE_MIDDLEWARE_ALIAS
caches = CacheHandler()
cache = caches[alias]


def cache_page(timeout=-1, cache_key=None):
    """
    页面缓存
    :param cache_key:
    :param timeout:
    :return:
    """

    def _deco(view_func):
        @wraps(view_func)
        def _handler(request, *args, **kw):
            key = cache_key
            """
            自定义一个key 
            """
            if not key:
                data = request.request.query_params
                key = ''
                for k, v in data.items():
                    key += ''.join(k) + "&" + ''.join(v) + "&"
            response = cache.get(key)
            if response is None:
                response = view_func(request, *args, **kw)
                cache.set(key, response, timeout)
            return response

        return _handler

    return _deco
